package org.lemon.transport.http.service.callback;

import lombok.extern.slf4j.Slf4j;
import org.lemon.transport.context.auth.ValidateDeviceCredentialsResponse;
import org.lemon.transport.context.auth.SessionInfoCreator;
import org.server.transport.gen.SessionProto;
import org.lemon.transport.context.service.TransportAuthServiceCallback;
import org.lemon.transport.context.service.TransportContext;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.context.request.async.DeferredResult;

import java.util.UUID;
import java.util.function.Consumer;

@Slf4j
public class DeviceAuthCallback<T> implements TransportAuthServiceCallback<ValidateDeviceCredentialsResponse> {

    private final TransportContext transportContext;

    private final DeferredResult<ResponseEntity<T>> responseWriter;

    private final Consumer<SessionProto.SessionInfoProto> onSuccess;

    public DeviceAuthCallback(TransportContext transportContext, DeferredResult<ResponseEntity<T>> responseWriter, Consumer<SessionProto.SessionInfoProto> onSuccess) {
        this.transportContext = transportContext;
        this.responseWriter = responseWriter;
        this.onSuccess = onSuccess;
    }

    @Override
    public void onSuccess(ValidateDeviceCredentialsResponse msg) {
        if (msg.hasDeviceInfo()) {
            onSuccess.accept(SessionInfoCreator.create(msg, transportContext, UUID.randomUUID()));
        } else {
            responseWriter.setResult(new ResponseEntity<>(HttpStatus.UNAUTHORIZED));
        }
    }

    @Override
    public void onError(Throwable e) {
        log.error("Failed to process request", e);
        responseWriter.setResult(new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR));
    }
}
